class Snake{
    constructor(el){
        this.el = el
        this.len = 20
        // 保存蛇移动的方向
        this.direction = 'right'
        // 蛇身体的对象，利用循环创建并追加页面
        this.snakeObj = [
            {x:5,y:3,color:'red',el:null},
            {x:4,y:3,color:'deeppink',el:null},
            {x:3,y:3,color:'deeppink',el:null}
        ]
    }

    // 创建蛇的原型方法
    snakeCreate(){
        // 重置蛇
        this.deleteSnake()
        for(let i = 0;i<this.snakeObj.length;i++){
            let snkObj = document.createElement('div')
            snkObj.style.position = 'absolute'
            snkObj.style.width = this.len + 'px'
            snkObj.style.height = this.len + 'px'
            snkObj.style.left = this.snakeObj[i].x * this.len + 'px'
            snkObj.style.top =  this.snakeObj[i].y * this.len + 'px'
            snkObj.style.backgroundColor =  this.snakeObj[i].color
            this.snakeObj[i].el = snkObj
            this.el.appendChild(snkObj)
        }
    }

    // 蛇移动
    snakeMove(){
        for(let i = this.snakeObj.length-1;i>0;i--){
            // console.log(this.snakeObj[i].x,this.snakeObj[i].y);
            this.snakeObj[i].x = this.snakeObj[i-1].x
            this.snakeObj[i].y = this.snakeObj[i-1].y
        }
        // 判断蛇头移动的方向
        switch (this.direction) {
            case 'top':
                this.snakeObj[0].y -=1
                break;
        
            case 'bottom':
                this.snakeObj[0].y +=1
                break;
        
            case 'left':
                this.snakeObj[0].x -=1
                break;
        
            case 'right':
                this.snakeObj[0].x +=1
                break;
            default:
                break;
        }
        this.snakeCreate()
    }

    // 键盘按下的方向
    snakeDirection(){
        document.onkeydown = (evt) => {
            let e = evt || window.event
            if(e.keyCode == '38'){
                this.direction = 'top'
            }
            if(e.keyCode == '40'){
                this.direction = 'bottom'
            }
            if(e.keyCode == '37'){
                this.direction = 'left'
            }
            if(e.keyCode == '39'){
                this.direction = 'right'
            }
        }
    }
    
  
    deleteSnake(){
        for(let i = 0;i<this.snakeObj.length;i++){
            // 判断蛇是否已经创建，创建之后才能删除
            if(this.snakeObj[i].el){
                this.el.removeChild(this.snakeObj[i].el)
            }
        }
    }


}